/*
 * Script containing the CreateEvent controller
 * 
 * Author: Chris Casola
 */

/**
 * Called when the user clicks the create event button. This function
 * grabs the information from the form, validates the values, creates
 * the local event entity, and then sends the event request to the server. 
 */
function CreateEventController(eventType) {
	if (document.getElementById('question').value == "") {
		alert('Question cannot be blank.');
		return;
	}
	
	if (eventType == "open") {
		var numChoices = parseInt(document.getElementById('openNumChoices').value);
		var numRounds = parseInt(document.getElementById('openNumRounds').value); 
		if ((numChoices > 8) || (numChoices < 3) || (numChoices == NaN)) {
			alert('Num choices must be between 3 and 8.');
			return;
		}
		if ((numRounds > 8) || (numRounds < 3) || (numRounds == NaN)) {
			alert('Num rounds must be between 3 and 8.');
			return;
		}
		if (document.getElementById('openUsername').value == "") {
			alert('Username cannot be blank.');
			return;
		}
			
		window.dlEvent = new Event(
			document.getElementById('openNumChoices').value,
			document.getElementById('openNumRounds').value		
		);
		window.dlEvent.eventType = "open";
		window.dlEvent.question = document.getElementById('question').value;
		window.dlEvent.username = document.getElementById('openUsername').value;		
	}
	else if (eventType == "closed") {
		var numChoices = parseInt(document.getElementById('closedNumChoices').value);
		var numRounds = parseInt(document.getElementById('closedNumRounds').value); 
		if ((numChoices > 8) || (numChoices < 3) || (numChoices == NaN)) {
			alert('Num choices must be between 3 and 8.');
			return;
		}
		if ((numRounds > 8) || (numRounds < 3) || (numRounds == NaN)) {
			alert('Num rounds must be between 3 and 8.');
			return;
		}
		if (document.getElementById('closedUsername').value == "") {
			alert('Username cannot be blank.');
			return;
		}
		
		window.dlEvent = new Event(
			document.getElementById('closedNumChoices').value,
			document.getElementById('closedNumRounds').value		
		);
		window.dlEvent.eventType = "closed";
		window.dlEvent.question = document.getElementById('question').value;
		window.dlEvent.username = document.getElementById('closedUsername').value;
		
		var choiceFields = document.getElementById('choices').children;
		for (var i=0; i < dlEvent.numChoices; i++) {
			dlEvent.choices[i].label = choiceFields[i].children[0].value;
		}
	}
	
	sendRequest(window.dlEvent.toJSON());
}
